package com.ruoyi.system.controller;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import org.springframework.http.HttpHeaders;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Files;
import com.ruoyi.system.service.IFilesService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件Controller
 * 
 * @author ruoyi
 * @date 2025-07-07
 */
@Controller
@RequestMapping("/system/files")
public class FilesController extends BaseController
{
    private String prefix = "system/files";

    @Autowired
    private IFilesService filesService;

    @RequiresPermissions("system:files:view")
    @GetMapping()
    public String files()
    {
        return prefix + "/files";
    }

    /**
     * 查询文件列表
     */
    @RequiresPermissions("system:files:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Files files)
    {
        startPage();
        List<Files> list = filesService.selectFilesList(files);
        return getDataTable(list);
    }

    /**
     * 导出文件列表
     */
    @RequiresPermissions("system:files:export")
    @Log(title = "文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Files files)
    {
        List<Files> list = filesService.selectFilesList(files);
        ExcelUtil<Files> util = new ExcelUtil<Files>(Files.class);
        return util.exportExcel(list, "文件数据");
    }

    /**
     * 新增文件
     */
    @RequiresPermissions("system:files:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存文件
     */
    @RequiresPermissions("system:files:add")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Files files, MultipartFile file) throws IOException
    {
        return toAjax(filesService.insertFiles(files, file));
    }

    /**
     * 批量新增保存文件
     */
    @RequiresPermissions("system:files:add")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping("/batchAdd")
    @ResponseBody
    public AjaxResult batchAddSave(MultipartFile[] files) throws IOException {
        return toAjax(filesService.insertFilesBatch(files));
    }

    /**
     * 修改文件
     */
    @RequiresPermissions("system:files:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Files files = filesService.selectFilesById(id);
        mmap.put("files", files);
        return prefix + "/edit";
    }

    /**
     * 修改保存文件
     */
    @RequiresPermissions("system:files:edit")
    @Log(title = "文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Files files)
    {
        return toAjax(filesService.updateFiles(files));
    }

    /**
     * 删除文件
     */
    @RequiresPermissions("system:files:remove")
    @Log(title = "文件", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(filesService.deleteFilesByIds(ids));
    }

    /**
     * 下载文件
     */
    @RequiresPermissions("system:files:download")
    @GetMapping("/download/{id}")
    public ResponseEntity<org.springframework.core.io.Resource> download(@PathVariable("id") Long id) throws IOException
    {
        // 1. 先获取文件信息
        Files fileInfo = filesService.selectFilesById(id);
        if (fileInfo == null || fileInfo.getGridFsId() == null) {
            return ResponseEntity.notFound().build();
        }

        // 2. 获取GridFS中的文件
        GridFsResource resource = filesService.downloadFile(id);
        if (resource == null || !resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 3. 处理文件名编码
        String filename = fileInfo.getFilename();
        if (filename == null || filename.isEmpty()) {
            filename = "unknown";
        }
        
        // 处理中文文件名
        filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");

        // 4. 设置响应头
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(fileInfo.getContentType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .contentLength(fileInfo.getFileSize())
                .body(resource);
    }

    /**
     * 预览文件（inline 展示）
     */
    @RequiresPermissions("system:files:download")
    @GetMapping("/preview/{id}")
    public ResponseEntity<org.springframework.core.io.Resource> preview(@PathVariable("id") Long id) throws IOException {
        Files fileInfo = filesService.selectFilesById(id);
        if (fileInfo == null || fileInfo.getGridFsId() == null) {
            return ResponseEntity.notFound().build();
        }

        GridFsResource resource = filesService.downloadFile(id);
        if (resource == null || !resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        String filename = fileInfo.getFilename();
        if (filename == null || filename.isEmpty()) {
            filename = "unknown";
        }

        filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(fileInfo.getContentType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                .contentLength(fileInfo.getFileSize())
                .body(resource);
    }
}
